package thenewscats;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Key;

@SuppressWarnings("serial")
public class ArticleServlet extends HttpServlet {


	public void doPost (HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException{
		process (req, resp);
	}
	
	public void doGet (HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException{
		process (req, resp);
	}
	

	
	protected void process (HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException{
		
		String action = req.getParameter("action");
		if (action.equals("view")){
			doView (req, resp);
			return; // it really shouldn't return
		} else if (action.equals("view-category")){
			doMultiView(req, resp);
			return;
		}//else
		//error
	}
	
	/* Returns a single article for viewing */
	protected void doView (HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException{
	
		String justCreated = req.getParameter("create");
		String keystring = req.getParameter("articlekey");
	
		Key articleKey = KeyFactory.stringToKey(keystring);
	
		ArticleFactory af = ArticleFactory.getInstance();
		Article a = af.getArticleByKey(articleKey);
	
		req.setAttribute("article", a);
		// flags whether article is just created
		if (justCreated != null && justCreated.equals("true")){
			req.setAttribute("created", true);			
		}
	
		RequestDispatcher dispatcher = req.getRequestDispatcher("viewArticle.jsp");
		dispatcher.forward(req, resp);
	}
	
	/* 
	 * Returns (up to) 10 latest article (summary version) given a category
	 * Hands it over to viewCategory.jsp to handle
	 * Category can be: news, local, world, sports, entertainment, and columns
	 */
	protected void doMultiView (HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException{
		
		String search_cat = req.getParameter("category");
		search_cat = search_cat.toLowerCase();
		
		ArticleFactory af = ArticleFactory.getInstance();
		List<Article> articles = af.getArticleByCategory(search_cat);
		
		req.setAttribute("articleList", articles);
		req.setAttribute("numReturned", articles.size());
		
		RequestDispatcher dispatcher = req.getRequestDispatcher("viewCategory.jsp");
		dispatcher.forward(req, resp);
	}
	

	
}
